<template>
  <div class="form-container">
    <!-- 弹窗标题（icon + 文字） -->
    <!-- form项json解析成html -->
    <parser
      ref="parser"
      :key="key"
      :form-conf.sync="formConf"
      :flow-conf="formPermission"
      @form-data="getFormData"
    />
    <!-- 审批人渲染 -->
    <custom-assignee
      ref="custom_assignee"
      v-if="!isFakeCustom"
      :validate.sync="customFlowConfig.validate"
      :assigneeList.sync="customFlowConfig.customAssigneeList"
      :customAssigneeGroup.sync="customFlowConfig.customAssigneeGroup"
      :modelKey="modelKey"
      :resourceBizId="bizId"
      :resourceProcessInstanceId="processInstanceId"
    ></custom-assignee>
    <!-- 流程comments -->
    <fks-flow-comments
      v-if="type !== 'add' && !isFakeCustom"
      class="no-flow-chart"
      :flowInfo="flowInfo"
      :data="comments"
      :dataSerise="commentSeries"
    ></fks-flow-comments>
    <div class="fawkes-custom-diagram-button" style="text-align: right">
      <fks-button
        v-if="!isFakeCustom"
        @click="flowCanvasVisible = true"
        icon="fks-icon-view"
        >查看流程</fks-button
      >
      <!--        <fks-button v-if="printFlag" :loading="getPdfLoading" @click="getPdf">打印</fks-button>-->
    </div>
    <fks-dialog
      title="流程图"
      :visible.sync="flowCanvasVisible"
      :append-to-body="true"
      width="960px"
      top="8vh"
      height="800px"
      v-cloak
    >
      <customFlowCanvas
        v-if="modelKey"
        :taskId="taskId"
        :bizId="bizId"
        :modelKey="modelKey"
        :flowInfo="flowInfo"
      ></customFlowCanvas>
    </fks-dialog>
  </div>
</template>

<script>
import Mix from '@/mixins/module'
import emmiter from 'fawkes-lib/lib/mixins/emitter'
import customAssignee from '@/modules/FormCenter/componentsWp/CustomAssignee'
import Parser from '@/modules/FormCenter/componentsWp/parser/Parser.vue'
import {
  getProcessHistory,
  initialCustomForm,
  getHistoryCustomFormConfig,
  getNodePermission,
  getHistoryNodes
} from '@/modules/FormCenter/api'
import customFlowCanvas from '@/modules/FormCenter/componentsWp/customFlowDiagram'
import downloadPdf from '@/utils/htmlToPdf'
export default {
  //自由流程表单 组件
  name: 'customForm',
  components: { Parser, customAssignee, customFlowCanvas },
  mixins: [Mix, emmiter],
  provide() {
    return {
      parentComponent: this
    }
  },
  props: [
    'moduleName',
    'formKey',
    'bizId',
    'processInstanceId',
    'taskKey',
    'taskId'
  ],
  data() {
    return {
      loading: true,
      isFakeCustom: false, // 是否是需要customForm组件解析的普通流程表单
      flowCanvasVisible: false,
      formConf: {},
      customFlowConfig: {
        customAssigneeGroup: {},
        customAssigneeList: [],
        validate: true,
        isCustom: true
      },
      modelKey: '', // 流程的modelKey
      comment: '', // 流程评论内容
      type: 'view', // 表单类型
      comments: [], // 表单评论信息
      // taskId: this.$route.params.taskId || '', // 任务ID
      // printFlag:this.$route.query.printFlag,
      commentSeries: {
        taskName: 'taskName',
        userName: 'asignee',
        realName: 'asigneeName',
        solveType: 'approveStateName',
        approveDate: 'approveDate',
        createDate: 'createDate',
        flag: 'approveState',
        comment: 'comment'
      },
      flowInfo: {
        xml: ''
      },
      // 输入此表单数据表对应的实体对象名
      entityName: '',
      // 表单数据
      formData: {},
      // taskNodeName: this.$route.query.taskName || '', // 当前任务节点名称
      formPermission: {}, // 当前任务节点 表单项权限
      formName: '', //表单名称
      key: +new Date(),
      //打印
      getPdfLoading: false
    }
  },
  methods: {
    // parse组件传来的数据
    getFormData(val) {
      this.formData = val
    },
    //根据当前taskId 查询当前节点表单字段权限信息
    getNodePermission() {
      return new Promise((resolve, reject) => {
        let taskKey = this.taskKey ? this.taskKey : 'fawkes_custom_flow_start'
        getNodePermission({ modelKey: this.modelKey, taskKey: taskKey }).then(
          (res) => {
            if (res.status) {
              resolve(JSON.parse(res.data.formPermission))
            }
          }
        )
      })
    },
    //初始化
    initial() {
      //重置 表单权限配置
      this.formPermission = {}
      // 发起状态查询获取最新表单json，非发起状态获取发起时的历史表单json
      getHistoryCustomFormConfig({
        formKey: this.formKey,
        bizId: this.bizId
      }).then(async (res) => {
        if (res.status && res.data) {
          //获取 表单基本属性、配置
          this.isFakeCustom = res.data.formType == 0 ? false : true
          this.formName = res.data.formName
          this.modelKey = res.data.modelKey
          this.$emit('update:moduleName', res.data.moduleName)

          this.customFlowConfig.isCustom = res.data.formType == 0 ? true : false
          let formObj = JSON.parse(res.data.formDesign).fields
          this.$refs.parser.dealResponseFormObj(formObj)
          this.formConf = {
            fields: formObj,
            ...JSON.parse(res.data.formDesign).formConf,
            disabled: true,
            isResource: true
          }
          //除了新增表单 其他类型时 还需要获取对应数据
          //根据当前taskKey和modelKey 查询当前节点表单字段权限信息
          if (!this.isFakeCustom) {
            this.formPermission = await this.getNodePermission()
            if (typeof this.formPermission === 'string') {
              this.formPermission = JSON.parse(this.formPermission)
            }
            //工作包查看资源时，所有的字段都设置为readonly只读
            Object.keys(this.formPermission).forEach((key) => {
              this.formPermission[key] = 'readonly'
            })
          }
          if (this.type !== 'add') {
            let data = await this.initialForm()
            this.$refs.parser.fillFormData(this.formConf, data) //数据回填
          }
          this.loading = false
          this.key = +new Date() //通过Key刷新
        } else {
          this.$message({
            type: 'error',
            message: this.LANG.NO_DATA,
            showClose: true
          })
        }
      })

      //获取流程comments
      if (this.type !== 'add') {
        //获取流程comments
        getProcessHistory({ processInstanceId: this.processInstanceId }).then(
          (res) => {
            if (res.status && res.data) {
              this.$emit('update:processInstanceId', res.data[0].id)
              this.comments = res.data.map((item) => {
                switch (item.approveState) {
                  case 'commit':
                    item.approveStateName = this.LANG.COMMIT
                    break
                  case 'todo':
                    item.approveStateName = this.LANG.TODO
                    break
                  case 'agree':
                    item.approveStateName = this.LANG.AGREE //同意
                    break
                  case 'skip':
                    item.approveStateName = this.LANG.SKIP //自动跳过
                    break
                  case 'reject':
                    item.approveStateName = this.LANG.REJECT //退回
                    break
                  default:
                    item.approveStateName
                }
                return item
              })
            } else {
              this.comments = []
            }
          }
        )
        getHistoryNodes({
          processInstanceId: this.processInstanceId,
          bizId: this.bizId
        }).then((res) => {
          this.flowInfo = Object.assign(this.flowInfo, res.data)
        })
      }
    },
    initialForm() {
      return new Promise((resolve, reject) => {
        let data = {
          formKey: this.formKey,
          id: this.bizId
        }
        initialCustomForm(data).then((res) => {
          if (res.status) {
            let returnData = {}
            returnData = JSON.parse(JSON.stringify(res.data))
            this.bizId = res.data.id
            //删除基本字段
            const deleteArray = [
              'create_by',
              'create_date',
              'delete_flag',
              // 'id',
              'update_by',
              'update_date'
            ]
            deleteArray.forEach((item) => {
              this.$delete(returnData, item)
            })
            //拿到所有数据字段后，如果字段权限没有 Hide 也没有 modify  则默认readonly
            if (this.type !== 'edit' && this.type !== 'view') {
              Object.keys(returnData).forEach((key) => {
                if (!Object.keys(this.formPermission).includes(key)) {
                  this.$set(this.formPermission, key, 'readonly')
                }
              })
            } else if (this.type === 'view') {
              this.formConf.fields.forEach((item) => {
                let vModel = item.__vModel__
                this.$set(this.formPermission, vModel, 'readonly')
              })
            }
            resolve(returnData)
          }
        })
      })
    },
    getPdf() {
      this.getPdfLoading = true
      let dom = this.$refs.dialog.$el.getElementsByClassName(
        'fks-dialog__body'
      )[0]
      let title = this.formName
      downloadPdf(dom, title).then(() => {
        this.getPdfLoading = false
      })
    }
  },
  watch: {
    formKey(val) {
      //初始化
      if (val) {
        this.initial()
      }
    }
  },
  mounted() {
    this.initial()
  }
}
</script>
<style lang="scss" scoped>
::v-deep .no-flow-chart {
  *[aria-controls*='pane-flow'] {
    display: none;
  }
}
[v-cloak]:not(body) {
  display: none;
}
.fawkes-custom-diagram-button {
  text-align: center;
}
.form-container {
  //height: 400px;
  //overflow-y: scroll;
  ::v-deep > .fks-row {
    margin: 0 !important;
  }
}
</style>
